
using System.Text;
using Backoffice.Application.Common.Interfaces;
using Backoffice.Application.Common.Services;
using Backoffice.Application.Services;
using Backoffice.Infrastructure.Repositories;
using Backoffice.Infrastructure.Secunity;
using BackOffice.Application;
using BackOffice.Application.Services;
using BackOffice.Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using UniversalAdmin.Shared.Extensions;
using Backoffice.Api.Middleware;


var builder = WebApplication.CreateBuilder(args);

// 添加CORS服务
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddControllers();

//注册应用层服务
builder.Services.AddApplication();


// 注册基础服务层
builder.Services.AddInfrastructure(builder.Configuration);


builder.Services.AddScoped<IPasswordHasher, PasswordHasher>();




// 1. 缓存
builder.Services.AddMemoryCache();
// 2. 注册 AuthService
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<ILogService, LogService>();


// 2. JWT 认证
var key = Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]?? string.Empty);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(opt =>
    {
        opt.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer   = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            ClockSkew        = TimeSpan.Zero
        };
    });

// 3. 授权
builder.Services.AddAuthorization();




// 2. 你的自定义服务
builder.Services.AddHttpContextAccessor();          // <-- 这里
builder.Services.AddScoped<ICurrentUser, CurrentUser>();



//分页
builder.Services.AddScoped<IUserRepository, UserRepository>();

var app = builder.Build();



// 4. 中间件顺序（必须在 Build 之后）
app.UseCors("AllowAll");
app.UseAuthentication();
app.UseAuthorization();

// 添加日志中间件
app.UseLogging();

// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

// 添加静态文件服务，用于文件下载
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads")),
    RequestPath = "/uploads"
});

app.UseAuthorization();

app.MapControllers();

try
{
    app.Run();
}
catch (Exception ex)
{
    Console.WriteLine($"Application failed to start: {ex.Message}");
    Console.WriteLine($"Stack trace: {ex.StackTrace}");
    throw;
}

